package com.heima.comment.service.impl;

import java.util.Date;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustException;
import com.heima.model.comment.dtos.CommentRepayDTO;
import com.heima.model.comment.dtos.CommentRepayLikeDTO;
import com.heima.model.comment.dtos.CommentRepaySaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vos.ApCommentRepayVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;


import java.util.*;
import java.util.stream.Collectors;

@Service
public class CommentRepayServiceImpl implements CommentRepayService {

    @Autowired
    GreenScan greenScan;

    @Autowired
    MongoTemplate mongoTemplate;


    /**
     * 加载评论回复列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {
        //1. 校验参数
        //   评论id不能为空  size为null 或 0 设置为10  最小日期为空 设置为当前
        if (dto == null || dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Integer size = dto.getSize();
        if (size == null || size <= 0) {
            size = 10;
        }
        if (dto.getMinDate() == null) {
            dto.setMinDate(new Date());
        }
        //2. 条件查询评论回复信息
        Query query = Query.query(Criteria.where("commentId")
                        .is(dto.getCommentId())
                        .and("createdTime")
                        .lt(dto.getMinDate()))
                .limit(size)
                .with(Sort.by(Sort.Direction.DESC, "createdTime"));
        //	条件:  commentId = 评论id and createdTime 小于 minDate  创建时间 降序  limit size
        List<ApCommentRepay> apCommentRepayList = mongoTemplate.find(query, ApCommentRepay.class);
        //3. 检查是否登录
        //	3.1 如果未登录直接 返回评论回复列表
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.okResult(apCommentRepayList);
        }
        //	3.2 如果登录，需要判断哪些回复点过赞
        //	思路:
        //	     基于当前列表 回复id集合  及  登录人id 查询回复点赞列表
        //回复id集合
        List<String> repayIdList = apCommentRepayList.stream()
                .map(ApCommentRepay::getId)
                .collect(Collectors.toList());
        //回复点赞列表
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(
                Query.query(Criteria.where("commentId").in(repayIdList)
                        .and("authorId").is(user.getId()))
                , ApCommentRepay.class);
        //	     遍历 当前回复列表，将每一个回复信息 封装成 vo
        if (CollectionUtils.isNotEmpty(apCommentRepayList)
                && CollectionUtils.isNotEmpty(apCommentRepays)) {
            List<String> repayIds = apCommentRepays.stream()
                    .map(ApCommentRepay::getCommentId).collect(Collectors.toList());
            //	     判断当前回复id 在点赞信息中是否存在，如果存在 operation设置为0 不存在不做处理
            return ResponseResult.okResult(apCommentRepayList.stream()
                    .map(commentRepay -> parseCommentRepayVO(commentRepay, repayIds)));
        }

        return ResponseResult.okResult(apCommentRepayList);
    }

    /**
     * 将commentRepay 转为 vo对象   根据likes情况判断是否点过赞
     *
     * @param apCommentRepay
     * @param repayIds
     * @return
     */
    private ApCommentRepayVO parseCommentRepayVO(ApCommentRepay apCommentRepay, List<String> repayIds) {
        ApCommentRepayVO apCommentRepayVO = new ApCommentRepayVO();
        BeanUtils.copyProperties(apCommentRepay, apCommentRepayVO);
        //遍历当前用户点赞列表
        if (repayIds.contains(apCommentRepayVO.getId())) {
            apCommentRepayVO.setOperation((short) 0);
        }
        return apCommentRepayVO;
    }

    /**
     * 保存评论回复
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) throws Exception {
        //1. 参数校验:
        //   是否登录  评论id是否为空  内容是否为空  内容是否大于140个字符
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //   回复内容安全校验
        String content = dto.getContent();
        ScanResult scanResult = greenScan.greenTextScan(content);
        String filteredContent = scanResult.getFilteredContent();
        //        简单: 不校验      普通: 阿里云内容检查，有问题抛异常     困难：阿里云内容检查，有问题替换为**
        if (filteredContent != null) {
            content = filteredContent;
        }
        //2. 根据评论id查询评论信息  检查是否存在
        Query query = Query.query(Criteria.where("id").is(dto.getCommentId()));
        ApComment apComment = mongoTemplate.findOne(query, ApComment.class);
        if (apComment == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "评论不存在！");
        }
        //3. 保存评论回复信息
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(user.getId());
        apCommentRepay.setAuthorName(user.getName());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setContent(content);
        apCommentRepay.setLikes(0);
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());
        mongoTemplate.save(apCommentRepay);
        //4. 修改评论信息中回复数量 + 1
        Update update = new Update();
        update.set("reply", apComment.getReply() + 1);
        mongoTemplate.updateMulti(query, update, ApComment.class);
        return ResponseResult.okResult();
    }

    /**
     * 保存评论回复点赞
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDTO dto) {
        //1. 校验参数
        //       回复id不能为空   operation 必须 0 或 1
        //       校验登录  (必须登录)
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //       校验回复信息是否存在
        ApCommentRepay apCommentRepay = mongoTemplate.findOne(
                Query.query(Criteria.where("id")
                        .is(dto.getCommentRepayId()))
                , ApCommentRepay.class);
        if (apCommentRepay == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "回复消息不存在");
        }
        //2. 如果是点赞  判断是否点过赞

        if (dto.getOperation().intValue() == 0) {
            //      点过赞提示请勿重复点赞
            ApCommentRepayLike apCommentRepayLike = mongoTemplate.findOne(
                    Query.query(Criteria.where("commentRepayId")
                            .is(dto.getCommentRepayId())
                            .and("authorId")
                            .is(user.getId())), ApCommentRepayLike.class);
            //      未点过赞， 保存点赞信息
            //       并将回复信息的点赞数量字段+1
            apCommentRepay.setLikes(apCommentRepay.getLikes() + 1);
            mongoTemplate.save(apCommentRepay);
            apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setAuthorId(user.getId());
            apCommentRepayLike.setCommentRepayId(apCommentRepay.getCommentId());
            apCommentRepayLike.setOperation(dto.getOperation());
            mongoTemplate.save(apCommentRepayLike);
        } else {
            //3. 如果是取消赞
            //      删除点赞信息
            mongoTemplate.remove(Query.query(Criteria.where("commentRepayId")
                    .is(dto.getCommentRepayId())
                    .and("authorId")
                    .is(user.getId())), ApCommentRepayLike.class);
            //     并将回复信息的点赞数量字段
            apCommentRepay.setLikes(
                    apCommentRepay.getLikes() <= 0 ? 0 : apCommentRepay.getLikes() - 1);
            mongoTemplate.save(apCommentRepay);
        }
        //4. 返回当前回复的最新点赞数量      数据的key:  likes
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("likes", apCommentRepay.getLikes());
        return ResponseResult.okResult(resultMap);
    }
}